---
title: "Syntax Comparison and Mapping"
description: "Learn how JavaScript syntax maps to Kotlin syntax, including variables, functions, control structures, and collections"
---

# Syntax Comparison and Mapping

Welcome to the first module of JavaScript to Kotlin conversion! In this module, we'll explore how JavaScript syntax maps to Kotlin syntax, helping you understand the fundamental differences and similarities between these two languages.

## Learning Objectives

By the end of this module, you'll be able to:
- Understand how JavaScript variable declarations map to Kotlin
- Convert JavaScript functions to Kotlin functions
- Map JavaScript control structures to Kotlin equivalents
- Work with Kotlin's type system and null safety
- Use Kotlin collections effectively
- Apply Kotlin's concise syntax patterns

## Variable Declarations and Type System

### JavaScript Variables vs Kotlin Variables

In JavaScript, you use `let`, `const`, and `var` for variable declarations. Kotlin has a more explicit type system with `val` (immutable) and `var` (mutable).

<UniversalEditor title="Variable Declarations Comparison" compare={true}>
```javascript !! js
// JavaScript variable declarations
let name = "LangShift";
const age = 25;
var isActive = true;

// JavaScript with type annotations (TypeScript style)
let message: string = "Hello";
const count: number = 42;
```

```kotlin !! kt
// Kotlin variable declarations
val name = "LangShift"  // Type inferred as String
var age = 25           // Type inferred as Int
val isActive = true    // Type inferred as Boolean

// Kotlin with explicit type annotations
val message: String = "Hello"
var count: Int = 42
```
</UniversalEditor>

### Key Differences

1. **Immutability**: `val` in Kotlin is like `const` in JavaScript, but `val` can be assigned once at runtime
2. **Type Inference**: Kotlin can infer types, but you can also specify them explicitly
3. **Null Safety**: Kotlin has built-in null safety, while JavaScript doesn't

<UniversalEditor title="Null Safety Comparison" compare={true}>
```javascript !! js
// JavaScript - no null safety
let user = null;
let name = user.name; // Runtime error!

// JavaScript with optional chaining
let name = user?.name; // Safe access
```

```kotlin !! kt
// Kotlin - built-in null safety
val user: String? = null
// val name = user.name // Compilation error!

// Kotlin safe call operator
val name = user?.name // Safe access, returns null if user is null

// Kotlin with non-null assertion
val name = user!!.name // Throws exception if user is null
```
</UniversalEditor>

## Function Declarations

### JavaScript Functions vs Kotlin Functions

JavaScript has multiple ways to declare functions, while Kotlin has a more consistent approach.

<UniversalEditor title="Function Declarations Comparison" compare={true}>
```javascript !! js
// JavaScript function declarations
function greet(name) {
    return "Hello, " + name + "!";
}

// Arrow function
const greetArrow = (name) => {
    return "Hello, " + name + "!";
};

// Arrow function with implicit return
const greetShort = name => "Hello, " + name + "!";

// Function with default parameters
function greetWithDefault(name = "World") {
    return "Hello, " + name + "!";
}
```

```kotlin !! kt
// Kotlin function declarations
fun greet(name: String): String {
    return "Hello, $name!"
}

// Kotlin function with expression body
fun greetShort(name: String) = "Hello, $name!"

// Kotlin function with default parameters
fun greetWithDefault(name: String = "World"): String {
    return "Hello, $name!"
}

// Kotlin lambda expression
val greetLambda: (String) -> String = { name -> "Hello, $name!" }
```
</UniversalEditor>

### Function Overloading

Kotlin supports function overloading, which JavaScript doesn't have natively.

<UniversalEditor title="Function Overloading" compare={true}>
```javascript !! js
// JavaScript - no native overloading
function add(a, b) {
    if (typeof a === 'string' && typeof b === 'string') {
        return a + b;
    }
    return a + b;
}

// Different approach needed for different signatures
function addNumbers(a, b) {
    return a + b;
}

function addStrings(a, b) {
    return a + b;
}
```

```kotlin !! kt
// Kotlin function overloading
fun add(a: Int, b: Int): Int {
    return a + b
}

fun add(a: String, b: String): String {
    return a + b
}

fun add(a: Double, b: Double): Double {
    return a + b
}

// Usage
val result1 = add(5, 3)        // Calls Int version
val result2 = add("Hello", "World") // Calls String version
val result3 = add(3.14, 2.86)  // Calls Double version
```
</UniversalEditor>

## Control Structures

### If Statements

Both languages have similar if statements, but Kotlin's if is an expression.

<UniversalEditor title="If Statements Comparison" compare={true}>
```javascript !! js
// JavaScript if statements
let age = 18;
let status;

if (age >= 18) {
    status = "adult";
} else {
    status = "minor";
}

// JavaScript ternary operator
let status2 = age >= 18 ? "adult" : "minor";
```

```kotlin !! kt
// Kotlin if expressions
val age = 18
val status = if (age >= 18) {
    "adult"
} else {
    "minor"
}

// Kotlin if as expression (no ternary operator needed)
val status2 = if (age >= 18) "adult" else "minor"
```
</UniversalEditor>

### When Expression (Kotlin) vs Switch Statement (JavaScript)

Kotlin's `when` is much more powerful than JavaScript's `switch`.

<UniversalEditor title="When vs Switch Comparison" compare={true}>
```javascript !! js
// JavaScript switch statement
let day = "Monday";
let message;

switch (day) {
    case "Monday":
        message = "Start of work week";
        break;
    case "Friday":
        message = "TGIF!";
        break;
    default:
        message = "Regular day";
}

// JavaScript with fall-through
switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        message = "Work day";
        break;
    default:
        message = "Weekend";
}
```

```kotlin !! kt
// Kotlin when expression
val day = "Monday"
val message = when (day) {
    "Monday" -> "Start of work week"
    "Friday" -> "TGIF!"
    else -> "Regular day"
}

// Kotlin when with multiple conditions
val message2 = when (day) {
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Work day"
    else -> "Weekend"
}

// Kotlin when with ranges
val number = 5
val result = when (number) {
    in 1..5 -> "Small number"
    in 6..10 -> "Medium number"
    else -> "Large number"
}
```
</UniversalEditor>

### Loops

Kotlin has more concise loop syntax than JavaScript.

<UniversalEditor title="Loops Comparison" compare={true}>
```javascript !! js
// JavaScript for loops
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// JavaScript for...of loop
const items = ["apple", "banana", "orange"];
for (const item of items) {
    console.log(item);
}

// JavaScript forEach
items.forEach(item => console.log(item));

// JavaScript while loop
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}
```

```kotlin !! kt
// Kotlin for loops
for (i in 0..4) {
    println(i)
}

// Kotlin for with range
for (i in 0 until 5) {
    println(i)
}

// Kotlin for with step
for (i in 0..10 step 2) {
    println(i)
}

// Kotlin for with collections
val items = listOf("apple", "banana", "orange")
for (item in items) {
    println(item)
}

// Kotlin forEach
items.forEach { item -> println(item) }

// Kotlin while loop
var count = 0
while (count < 5) {
    println(count)
    count++
}
```
</UniversalEditor>

## Collections

### Arrays and Lists

JavaScript arrays are more flexible, while Kotlin has different collection types for different use cases.

<UniversalEditor title="Collections Comparison" compare={true}>
```javascript !! js
// JavaScript arrays
let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana"];

// Adding elements
numbers.push(6);
fruits.push("orange");

// Removing elements
numbers.pop();
fruits.splice(1, 1);

// Array methods
let doubled = numbers.map(x => x * 2);
let evenNumbers = numbers.filter(x => x % 2 === 0);
let sum = numbers.reduce((acc, x) => acc + x, 0);

// Array destructuring
let [first, second, ...rest] = numbers;
```

```kotlin !! kt
// Kotlin lists
val numbers = listOf(1, 2, 3, 4, 5)
val fruits = mutableListOf("apple", "banana")

// Adding elements (mutable list)
fruits.add("orange")

// Removing elements
fruits.removeAt(1)

// List operations
val doubled = numbers.map { it * 2 }
val evenNumbers = numbers.filter { it % 2 == 0 }
val sum = numbers.reduce { acc, x -> acc + x }

// List destructuring
val (first, second, *rest) = numbers

// Kotlin arrays
val numberArray = arrayOf(1, 2, 3, 4, 5)
val stringArray = arrayOf("hello", "world")
```
</UniversalEditor>

### Maps and Objects

JavaScript objects are similar to Kotlin maps, but with different syntax.

<UniversalEditor title="Maps and Objects Comparison" compare={true}>
```javascript !! js
// JavaScript objects
let person = {
    name: "John",
    age: 30,
    city: "New York"
};

// Accessing properties
console.log(person.name);
console.log(person["age"]);

// Adding properties
person.job = "Developer";

// Object destructuring
let { name, age } = person;

// JavaScript Map
let userMap = new Map();
userMap.set("id", 1);
userMap.set("name", "Alice");
userMap.set("email", "alice@example.com");

console.log(userMap.get("name"));
```

```kotlin !! kt
// Kotlin maps
val person = mapOf(
    "name" to "John",
    "age" to 30,
    "city" to "New York"
)

// Accessing values
println(person["name"])
println(person["age"])

// Mutable map
val mutablePerson = mutableMapOf(
    "name" to "John",
    "age" to 30
)

// Adding entries
mutablePerson["job"] = "Developer"

// Map destructuring
for ((key, value) in person) {
    println("$key: $value")
}

// Kotlin data class (better than maps for structured data)
data class Person(
    val name: String,
    val age: Int,
    val city: String
)

val john = Person("John", 30, "New York")
println(john.name)
```
</UniversalEditor>

## String Templates and Interpolation

Kotlin's string templates are more powerful than JavaScript's template literals.

<UniversalEditor title="String Templates Comparison" compare={true}>
```javascript !! js
// JavaScript template literals
let name = "World";
let greeting = `Hello, ${name}!`;

// JavaScript with expressions
let a = 5;
let b = 3;
let result = `Sum: ${a + b}`;

// JavaScript with function calls
function getGreeting(name) {
    return `Hello, ${name}!`;
}

let message = getGreeting("Alice");
```

```kotlin !! kt
// Kotlin string templates
val name = "World"
val greeting = "Hello, $name!"

// Kotlin with expressions
val a = 5
val b = 3
val result = "Sum: ${a + b}"

// Kotlin with function calls
fun getGreeting(name: String) = "Hello, $name!"

val message = getGreeting("Alice")

// Kotlin with complex expressions
val items = listOf("apple", "banana", "orange")
val itemList = "Items: ${items.joinToString(", ")}"
```
</UniversalEditor>

## Practice Exercises

### Exercise 1: Convert JavaScript Function to Kotlin

Convert this JavaScript function to Kotlin:

```javascript
function calculateTotal(items) {
    let total = 0;
    for (let item of items) {
        total += item.price * item.quantity;
    }
    return total;
}
```

<UniversalEditor title="Exercise 1 Solution" compare={true}>
```javascript !! js
function calculateTotal(items) {
    let total = 0;
    for (let item of items) {
        total += item.price * item.quantity;
    }
    return total;
}

// Usage
const items = [
    { name: "Apple", price: 1.50, quantity: 3 },
    { name: "Banana", price: 0.75, quantity: 2 }
];
console.log(calculateTotal(items));
```

```kotlin !! kt
fun calculateTotal(items: List<Item>): Double {
    var total = 0.0
    for (item in items) {
        total += item.price * item.quantity
    }
    return total
}

// Data class for structured data
data class Item(
    val name: String,
    val price: Double,
    val quantity: Int
)

// Usage
val items = listOf(
    Item("Apple", 1.50, 3),
    Item("Banana", 0.75, 2)
)
println(calculateTotal(items))
```
</UniversalEditor>

### Exercise 2: Convert JavaScript Array Operations to Kotlin

Convert these JavaScript array operations to Kotlin:

```javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenSquares = numbers
    .filter(n => n % 2 === 0)
    .map(n => n * n)
    .reduce((sum, n) => sum + n, 0);
```

<UniversalEditor title="Exercise 2 Solution" compare={true}>
```javascript !! js
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenSquares = numbers
    .filter(n => n % 2 === 0)
    .map(n => n * n)
    .reduce((sum, n) => sum + n, 0);

console.log(evenSquares); // 220
```

```kotlin !! kt
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenSquares = numbers
    .filter { it % 2 == 0 }
    .map { it * it }
    .reduce { sum, n -> sum + n }

println(evenSquares) // 220
```
</UniversalEditor>

## Key Takeaways

1. **Type Safety**: Kotlin provides compile-time type checking, while JavaScript is dynamically typed
2. **Null Safety**: Kotlin's null safety prevents null pointer exceptions at compile time
3. **Immutability**: Use `val` for immutable variables and `var` for mutable ones
4. **Expression-based**: Kotlin's `if` and `when` are expressions, not just statements
5. **Collections**: Kotlin has different collection types for different use cases
6. **String Templates**: Kotlin's string interpolation is more powerful than JavaScript's
7. **Function Overloading**: Kotlin supports function overloading, JavaScript doesn't

## Next Steps

In the next module, we'll explore the JVM ecosystem and toolchain, including:
- Understanding the JVM platform
- Working with Gradle build system
- Package management and dependencies
- IDE integration and debugging tools

This foundation in syntax comparison will help you understand how to translate your JavaScript knowledge to Kotlin effectively. 